<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.userName" placeholder="姓名" style="width: 80px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.loginName" placeholder="登陆名" style="width: 80px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <base-select :dictType="'BASE_STATUS'" v-model="listQuery.status" style="width: 140px" class="filter-item" @change="handleFilter">
      </base-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button> 
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        {{ $t('table.reviewer') }}
      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:10px"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('table.id')" prop="id" sortable="true" align="center" width="80" v-if="false" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="110px" prop="userName" sortable="true" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登陆名" width="110px" prop="loginName" sortable="true" align="center">
        <template slot-scope="{row}">
          <span>{{ row.loginName  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="110px" prop="phone"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column  label="邮箱" width="110px" prop="email" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" class-name="status-col" prop="sex"  width="100px" align="center">
        <template slot-scope="{row}">
            <span >{{ row.sex | dictValueFilter('SEX') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" width="110px" prop="birthday" align="center">
        <template slot-scope="{row}">
            <span>{{ row.birthday }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" prop="roleNames" width="110px">
        <template slot-scope="{row}">
            <span >{{ row.roleNames }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" prop="orgName" width="110px">
        <template slot-scope="{row}">
            <span >{{ row.orgName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" prop="status"  width="100px" align="center">
        <template slot-scope="{row}">
            <span >{{ row.status | dictValueFilter('BASE_STATUS') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini"    @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button  size="mini" type="danger" :disabled="row.loginName=='admin'?true:false"  @click="handleDelete(row,$index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" >
      <el-form ref="dataForm" :rules="rules" :model="temp"  label-width="120px" style="width: 300px; margin-left:50px;">
        <el-form-item label="用户名" prop="userName">
            <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
            <el-input v-model="temp.loginName" />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <base-select :dictType="'SEX'" v-model="temp.sex"  class="filter-item" >
          </base-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="角色" prop="roleCodesFront">
            <el-select v-model="temp.roleCodesFront"  @change="$forceUpdate()" multiple placeholder="请选择" >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="所属机构" prop="orgId">
          <el-tree
            :data="orgData"
            show-checkbox
            node-key="id"
            ref="tree"
            check-strictly
            highlight-current
            @check-change="handleOrgClick" 
            :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="temp.birthday" type="date" value-format="yyyy-MM-dd" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item :label="$t('table.status')">
            <base-select :dictType="'BASE_STATUS'" v-model="temp.status" class="filter-item" placeholder="Please select">
            </base-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList , create, update, del,selectOne } from '@/api/rbac/User'
import { all as allRole}  from '@/api/rbac/Role'
import { all as allOrg}  from '@/api/rbac/Org'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import BaseSelect from '@/components/Dict'



export default {
  name: 'user',
  components: { Pagination,BaseSelect },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: 'id desc',
        userName :'',
        loginName:'',
        status:''
      },
      importanceOptions: [1, 2, 3],
      roleList: [],
      temp: {
        id: undefined,
        userName: '',
        loginName: '',
        birthday: new Date(),
        sex: '',
        phone: '',
        roleCodesFront:[],
        roleCodes:'',
        roleNames:'',
        status: '',
        orgId:'',
        orgName:''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      rules: {
        userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        birthday: [{  required: true, message: '出生日期不能为空', trigger: 'change' }],
        loginName: [{ required: true, message: '登陆名不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      defaultProps: {
          children: 'children',
          label: 'orgName'
      },
      orgData:[]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
      allRole().then(response =>{
        this.roleList = response.data
      })
      allOrg().then(response =>{
        this.orgData = response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
    //   if (prop === 'id') {
        this.sortBy(prop,order)
    //   }
    },
    sortBy(prop,order) {
      if (order === 'ascending') {
        this.listQuery.sort = prop + ' asc'
      } else {
        this.listQuery.sort = prop + ' desc'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        loginName: '',
        birthday: new Date(),
        sex: '',
        phone: '',
        roleCodesFront:[],
        roleCodes:'',
        roleNames:'',
        status: '',
        orgId:'',
        orgName:''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.roleCodes = this.temp.roleCodesFront.join(',')
          this.temp.roleNames = this.processRoleNames(this.temp.roleCodesFront);
          const orgCheckedArray = this.$refs.tree.getCheckedNodes()
          if(orgCheckedArray.length>0){
            temp.orgId = orgCheckedArray[0].id
            temp.orgName = orgCheckedArray[0].orgName
          }
          create(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    
    handleUpdate(row) {
      selectOne(row.id).then(response =>{
        this.temp = response.data
        const array = response.data.roleCodes.split(',')
        var intArray = [] // 类型转换
        array.forEach(element => {
          intArray.push(parseInt(element))
        });
        this.temp.roleCodesFront =  intArray
        // this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
            this.$refs.tree.setCheckedKeys([this.temp.orgId]);
        })
      }).catch(error =>{
           this.$notify({
              title: '失败',
              message: error,
              type: 'error',
              duration: 2000
            })
      })  
      
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.roleCodes = this.temp.roleCodesFront.join(',')
          tempData.roleNames = this.processRoleNames(this.temp.roleCodesFront);
          const orgCheckedArray = this.$refs.tree.getCheckedNodes()
          if(orgCheckedArray.length>0){
            tempData.orgId = orgCheckedArray[0].id
            tempData.orgName = orgCheckedArray[0].orgName
          }
          update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    processRoleNames(roleCodesArray){
      let roleNamesArray = []
      for (let i =0;i<roleCodesArray.length;i++){
            this.roleList.find(item =>{
              if(item.id == roleCodesArray[i]){
                roleNamesArray.push(item.name)
              }
            })
          }
          return roleNamesArray.join(',')
    },
    handleDelete(row, index) {
        del(row.id).then(response =>{
            this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
            })
            this.getList()
        }).catch(error =>{
            this.$notify({
                title: '删除失败',
                message: error,
                type: 'error',
                duration: 2000
            })
        })
    },
    handleOrgClick(data,checked, node){
      if(checked){
        this.$refs.tree.setCheckedNodes([]);
        this.$refs.tree.setCheckedNodes([data]);
      }
    },
    handleOpen(){
      // this.$nextTick(function() {
        this.$refs.tree.setCheckedKeys([this.temp.orgId]);
      // })

      
    },
    // handleFetchPv(pv) {
    //   fetchPv(pv).then(response => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },
    // handleDownload() {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const data = this.formatJson(filterVal)
    //     excel.export_json_to_excel({
    //       header: tHeader,
    //       data,
    //       filename: 'table-list'
    //     })
    //     this.downloadLoading = false
    //   })
    // },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `${key}`+' desc' ?  'descending':'ascending'
    }
  }
}
</script>
